<template>
  <div class="app-container-flex">
    <NewFullScreen
      v-model="showDialog"
      :title="title"
      @returnBack="$emit('returnModify')"
    >
      <template v-slot:full-button>
        <el-button @click="save()">保存</el-button>
      </template>
      <div class="model-panel">
        <div class="model-panel-title">
          <p>{{ $t("basic_information") }}</p>
        </div>
        <div class="model-panel-body">
          <!-- form -->
          <page-form
            class="paddingBox order-model-formBox flex_wrap_start_start"
            v-model:ref-obj="formInfo.ref"
            :disabled="formInfo.disabled"
            :data="formInfo.data"
            :field-list="formInfo.fieldList"
            :rules="formInfo.rules"
            :label-width="formInfo.labelWidth"
          >
            <template v-slot:form-deptUserName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择部门人员"
                v-model="formInfo.data.deptUserName"
              >
                <template #append>
                  <el-icon @click="openUserWindow"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-patrolUserName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择巡检人员"
                v-model="formInfo.data.patrolUserName"
              >
                <template #append>
                  <el-icon @click="openUserWindowAll"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>
            <template v-slot:form-useDeptName>
              <el-input
                type="input"
                :disabled="true"
                class="not-mongolia"
                placeholder="请选择部门"
                v-model="formInfo.data.useDeptName"
              >
                <template #append>
                  <el-icon @click="addDept"><MoreFilled /></el-icon>
                </template>
              </el-input>
            </template>

            <template v-slot:form-patrolDate>
              <el-date-picker
                v-model="formInfo.data.patrolDate"
                type="datetime"
                value-format="YYYY-MM-DD HH:mm:ss"
                placeholder="选择日期时间"
              >
              </el-date-picker>
            </template>
          </page-form>
        </div>
      </div>

      <div class="model-panel">
        <div class="model-panel-title">
          <Tooltip :text="'巡检设备'" />
        </div>
        <div class="model-panel-body">
          <!-- 条件栏 -->
          <div>
            <NewPageFilter
              v-model:query="filterInfo.query"
              :filter-btn="filterInfo.list"
            >
              <template v-slot:filter-addAsset>
                <el-button
                  :disabled="!formInfo.data.useDeptName"
                  @click="addAsset()"
                  >添加设备</el-button
                >
              </template>
              <template v-slot:filter-removeAsset>
                <el-button
                  :disabled="!tableInfo.selections.length"
                  @click="removeAsset()"
                  >删除设备</el-button
                >
              </template>
            </NewPageFilter>
            <div class="flex_full_item">
              <el-form :model="tableInfo" ref="tableForm" style="width: 100%">
                <!-- 表格 -->
                <page-table
                  :refresh="tableInfo.refresh"
                  :init-curpage="tableInfo.initCurpage"
                  v-model:data="tableInfo.data"
                  :pager="false"
                  :tabIndex="true"
                  :field-list="tableInfo.fieldList"
                  :handle="tableInfo.handle"
                  :row-class-name="tableRowClassName"
                  @handleEvent="handleEvent"
                >
                  <template v-slot:col-patrolRecoredDetailResult="scope">
                    <el-input
                      v-model="scope.row.patrolRecoredDetailResult"
                      style="width: 100%"
                      maxlength="100"
                      placeholder=""
                    ></el-input>
                  </template>
                </page-table>
              </el-form>
            </div>
          </div>
        </div>
      </div>
    </NewFullScreen>
    <!-- 部门 -->
    <SelectDept
      v-if="selectDept.visible"
      v-model:show-dialog="selectDept.visible"
      :check-box="false"
      :highlight-row="true"
      :query="selectDept.query"
      :save-empty="true"
      title="选择部门"
      @callback="callDept"
    />
    <!-- 部门人员 -->
    <SelectUsers
      v-if="selectUserInfo.visible"
      v-model:showDialog="selectUserInfo.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :query="selectUserInfo.query"
      :checkedRowList="selectUserInfo.checkedRowList"
      :check-box="true"
      :highlight-row="true"
      @callback="selectUserCallback"
    />
    <SelectUsers
      v-if="selectUserInfoAll.visible"
      v-model:showDialog="selectUserInfoAll.visible"
      :api="getRrgUserList"
      :saveEmpty="true"
      :query="selectUserInfoAll.query"
      :checkedRowList="selectUserInfoAll.checkedRowList"
      :check-box="true"
      :highlight-row="true"
      @callback="selectUserCallbackAll"
    />
    <!--设备选择-->
    <Select-asset
      v-if="selectAssetInfo.visible"
      v-model:show-dialog="selectAssetInfo.visible"
      :tableKey="selectAssetInfo.tableKey"
      :query="selectAssetInfo.query.queryMap"
      :query-params="selectAssetInfo.query.queryParams"
      table-key="analysisPlanAddCoreAsset-com.slip.spd.entity.vo.core.CoreAssetVO"
      :check-box="selectAssetInfo.checkBox"
      :highlightRow="true"
      @callback="callBackAsset"
    />
  </div>
</template>

<script setup name="patrolRecordRegistrationModify">
import PageForm from "@/components/PageForm/index";
import PageTable from "@/components/PageTable/index";
import {
  createPatrolRecored,
  updatePatrolRecored,
  getPatrolRecoredById,
} from "@/api/patrol";
import { getDeptUserAll, getRrgUserList } from '@/api/base'
import { getUseReturnApplicationDetailCustomizeList } from "@/api/use";

import { getCustomizeSetting } from "@/api/customize";
import SelectUsers from "@/components/SelectUsers/index";

const { proxy } = getCurrentInstance();
const emit = defineEmits();

const Tooltip = defineAsyncComponent(() =>
  import("@/components/Tooltip/index")
);

const props = defineProps(["visible", "title", "id"]);

const timePickerOptions = ref({});
const formRefs = ref([]);
const formInfo = reactive({
  ref: null,
  data: {
    status: 0,
    remindTask: 1,
  },
  fieldList: [
    // useDeptId
    {
      label: "使用部门",
      value: "useDeptName",
      type: "slot",
    },
    {
      label: "部门人员",
      value: "deptUserName",
      type: "slot",
    },
    {
      label: "巡检人员",
      value: "patrolUserName",
      type: "slot",
    },
    {
      label: "巡检时间",
      value: "patrolDate",
      type: "slot",
    },

    {
      label: "备注",
      value: "remark",
      type: "textarea",
    },
    {
      label: "存在问题",
      value: "existProblem",
      type: "textarea",
    },
    {
      label: "整改意见和措施",
      value: "suggestion",
      type: "textarea",
    },
  ],
  rules: {
    useDeptName: [{ required: true, message: "请选择部门", trigger: "change" }],
    // deptUserName: [
    //   { required: true, message: '请选择部门人员', trigger: 'change' },
    // ],
    patrolUserName: [
      { required: true, message: "请选择巡检人员", trigger: "change" },
    ],
    patrolDate: [
      { required: true, message: "请选择巡检时间", trigger: "change" },
    ],
  },
  labelWidth: "120px",
});
const selectDept = ref({
  visible: false,
  query: {
    status: 1,
    deptAuth: "id",
  },
  row: {},
  index: 0,
  code: "",
});
const filterInfo = reactive({
  query: {
    customizeUserVO: {},
    queryMap: {
      orderId: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: props.id,
      },
    },
  },
  list: [
    { label: "添加设备", type: "slot",value: 'addAsset', event: addAsset },
    { type: "slot", value: "removeAsset" },
  ],
});
const tableInfo = reactive({
  refresh: 1,
  initCurpage: 1,
  data: [],

  selections: [],

  fieldList: [],
  handle: {
    fixed: "right",
    label: "操作",
    width: "100",
    btList: [
      {
        label: "删除",
        event: removeAsset,
        popconfirmText: "删除后将改变数据,是否继续？",
        show: true,
      },
    ],
  },
});
const selectAssetInfo = ref({
  visible: false,
  checkBox: true,
  query: {
    queryMap: {
      id: {
        queryType: "NOT_IN",
        queryCategory: "AND",
        value: "",
      },
      assetStatus: {
        queryType: "IN",
        queryCategory: "AND",
        value: "1,3",
      },
      assetSourceAuth: {
        asTbName: "core_asset,core_asset",
        columnName: "use_dept_id,depot_id",
        queryType: "IN",
        queryCategory: "AND",
        value: "assetSourceAuth",
      },
      isMaintenance: {
        queryType: "EQUALS",
        queryCategory: "AND",
        value: "1",
      },
      status: {
        queryType: "IN",
        queryCategory: "AND",
        value: "3",
      },
    },
    queryParams: {
      assetAnalysisFilter: 1,
      deptId: "",
      analysisPlanIdNotIn: "",
    },
  },
});
const selectUserInfo = reactive({
  visible: false,
  saveEmpty: true,
  checkedRowList: '',
  query: {
    hasAllDept: 1,
    deptId: "",
  }
});
const selectUserInfoAll = reactive({
  visible: false,
  saveEmpty: true,
  checkedRowList: '',
  query: {
    hasAllDept: 1,
    deptId: "",
  },
});

const showDialog = computed({
  get() {
    return props.visible;
  },
  set(newValue) {
    emit("update:visible", newValue); // 更新父组件visible
  },
});

let obj = {
  assetName: {
    label: "设备名称",
    value: "assetName",
    componentType: "input",
    type: "column",
    show: false,
    hidden: true,
  },
  patrolRecoredDetailResult: {
    label: "巡检结果",
    value: "patrolRecoredDetailResult",
    componentType: "input",
    type: "slot",
    show: false,
    hidden: true,
  },
};
tableInfo.fieldList = Object.values({
  ...proxy.$fn.deepClone(proxy.$fieldfList.FieldList),
  ...obj,
});
getCustomize();

onMounted(() => {
  timePickerOptions.value = {
    disabledDate(time) {
      return time.getTime() < Date.now() - 8.64e7;
    },
  };
  formRefs.value = [proxy.$refs["itemsTableForm"], formInfo.ref];
  console.log(formRefs.value);
  proxy.$nextTick(() => {
    if (!props.id) {
      formInfo.fieldList = formInfo.fieldList.filter(
        (item) => item.value !== "orderNo"
      );
    }
  });
});

//部门人员
function openUserWindow() {
  if (!formInfo.data.useDeptName) {
    proxy.$message({
      message: "请选择部门",
      type: "warning",
    });
    return;
  }
  selectUserInfo.visible = true;
  selectUserInfo.query.deptId = formInfo.data.useDeptId;
}
function openUserWindowAll() {
  selectUserInfoAll.visible = true;
}
function selectUserCallback(arr) {
  console.log(arr);

  if (arr && arr.length) {
    let names = [];
    let ids = [];
    arr.map((i) => {
      names.push(i.name);
      ids.push(i.id);
    });
    formInfo.data["deptUserName"] = names.join(",");
    formInfo.data["deptUserIdList"] = ids;
    selectUserInfo.checkedRowList = arr
  } else {
    formInfo.data["deptUserName"] = "";
    formInfo.data["deptUserIdList"] = [];
    selectUserInfo.checkedRowList = ''
  }
}
function selectUserCallbackAll(arr) {
  console.log(arr);
  if (arr && arr.length) {
    let names = [];
    let ids = [];
    arr.map((i) => {
      names.push(i.name);
      ids.push(i.id);
    });
    formInfo.data["patrolUserName"] = names.join(",");
    formInfo.data["patrolUserIdList"] = ids;
    selectUserInfoAll.checkedRowList = arr
  } else {
    formInfo.data["patrolUserName"] = "";
    formInfo.data["patrolUserIdList"] = "";
    selectUserInfoAll.checkedRowList = ''
  }
  // patrolUserIdList
}

function addAsset() {
  if (tableInfo.data.length) {
    selectAssetInfo.value.query.queryMap.id.value = tableInfo.data
      .map((item) => item.assetId)
      .toString();
  } else {
    selectAssetInfo.value.query.queryMap.id.value = "";
  }
  if (formInfo.data.analysisType == 0) {
    selectAssetInfo.value.checkBox = false;
  } else {
    selectAssetInfo.value.checkBox = true;
  }
  selectAssetInfo.value.query.queryParams.deptId = formInfo.data.useDeptId;
  selectAssetInfo.value.query.queryParams.analysisPlanIdNotIn = props.id;
  selectAssetInfo.value.visible = true;
}
function callBackAsset(data) {
  if (formInfo.data.analysisType == 0) {
    data.assetId = data.id;
    tableInfo.data = [data];
  } else {
    data.forEach((item) => {
      item.assetId = item.id;
    });
    tableInfo.data = data.concat(tableInfo.data);
  }
}
function removeAsset(row = undefined) {
  if (row) {
    tableInfo.data = tableInfo.data.filter((item) => item !== row);
  } else {
    proxy
      .$confirm("删除后将改变数据,是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
      .then(() => {
        tableInfo.data = tableInfo.data.filter((row) => {
          return !tableInfo.selections.includes(row);
        });
      });
  }
}

function tableRowClassName({ row = undefined }) {
  if (row.isChoice) {
    return "success-row";
  } else {
    return "";
  }
}

function getMain() {
  getPatrolRecoredById(props.id).then((resp) => {
    if (resp && resp.success) {
      formInfo.data = resp.data;
      tableInfo.data = resp.data.patrolRecoredEditDetailList
      if(resp.data.deptUserIdList && resp.data.deptUserIdList.length) {
        getUserAllList(formInfo.data.deptUserIdList)
      }
      if(resp.data.patrolUserIdList && resp.data.patrolUserIdList.length) {
        getUserAllListAll(formInfo.data.patrolUserIdList)
      }
    }
  });
  filterInfo.query.queryMap.orderId.value = props.id;
}
function getUserAllList(ids) {
  let params = {
    idIn: ids.join(','),
  }
  getDeptUserAll(params).then((res) => {
    if (res && res.success) {
      selectUserInfo.checkedRowList = res.data
    }
  })
}
function getUserAllListAll(ids) {
  let params = {
    idIn: ids.join(','),
  }
  getDeptUserAll(params).then((res) => {
    if (res && res.success) {
      selectUserInfoAll.checkedRowList = res.data
    }
  })
}
function getCustomize() {
  let param = {
    tableKey:
      "patrolRecoredEditDetailVO-com.slip.spd.entity.vo.patrol.PatrolRecoredEditDetailVO",
  };
  tableInfo.isSysGroup = false;
  getCustomizeSetting(param).then((res) => {
    if (res && res.success) {
      let data = res.data;
      tableInfo.fieldList = proxy.$fn.setFieldList(
        tableInfo.fieldList,
        data.detail
      );
      for (let key in data.detail) {
        if (data.detail[key].sysGroupLevel > 0) {
          tableInfo.isSysGroup = true;
        }
      }
      filterInfo.query.customizeUserVO = data;
    }
  });
  if (props.id) {
    getMain();
  }
}

// 触发事件
function handleEvent(event, data) {
  switch (event) {
    case "tableCheck":
      tableInfo.selections = data;
      break;
  }
}

//保存
function save() {
  proxy.$fn
    .checkForm(formRefs.value)
    .then(() => {
      if (!(tableInfo.data && tableInfo.data.length)) {
        proxy.$message({
          message: "请添加设备",
          type: "warning",
        });
        return;
      }
      const data = formInfo.data;
      data.patrolRecoredDetailList = [];
      if (tableInfo.data.length) {
        tableInfo.data.forEach((item) => {
          data.patrolRecoredDetailList.push({
            assetId: item.id || item.assetId,
            result: item.patrolRecoredDetailResult || "",
          });
        });
      }
      const api = data.id ? updatePatrolRecored : createPatrolRecored;
      console.log(api);
      api(data).then((resp) => {
        if (resp && resp.success) {
          showDialog.value = false;
          emit("returnModify");
        }
      });
    })
    .catch((error) => {
      console.log(error);
    });
}
function addDept() {
  selectDept.value.visible = true;
}
function callDept(row) {
  console.log(row);
  formInfo.data.useDeptName = row.name;
  formInfo.data.useDeptId = row.id;
  selectDept.value.visible = false;
  // 清空部门人员 表格
  formInfo.data["deptUserName"] = "";
  formInfo.data["deptUserIdList"] = [];

  tableInfo.data = [];
}
</script>

<style scoped>
.form-date {
  width: 50%;
  display: inline-block;
}
.form-date-type {
  width: 50%;
  display: inline-block;
}
.form-input {
  margin: 15px auto;
}
</style>
